<?php

#    Document   : admin
#    Created on : May 4, 2011, 9:32:14 PM
#    Author     : ClarkT AKA FalleN
#    Company    : Amodity
#    Web        : http://www.amodity.com
#    Copyright  : 2011
/**

 * @property CI_Loader $load

 * @property CI_Form_validation $form_validation

 * @property CI_Input $input

 * @property CI_Email $email

 * @property CI_DB_active_record $db

 * @property CI_DB_forge $dbforge

 *  @property CI_Session $session

 * @property CI_FTP $ftp

 */

class Admin extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('auth');
        $this->_prev_url();
        $this->load->helper('config_file');
        if (ENVIRONMENT == 'development') {
            $this->output->enable_profiler(TRUE);
        }
    }

    //--------------------------------------------------------------------

    function index() {
        //is user logged in
        $this->_is_logged_in();
        //check permissions
        $this->_is_admin();

        $this->template->set('title', lang('admin_dashboard'));
        $this->template->set('page_title', lang('admin_dashboard'));
        $this->template->load('templates/admin_template', 'admin_dashboard', null, 'admin');
    }

    //--------------------------------------------------------------------
    //
    //User Functions
    //
    
    function login() {
        $this->template->set('title', lang('g_login'));
        $this->template->load('templates/admin_login_template', 'admin_login', null, 'admin');
    }

    //--------------------------------------------------------------------

    function logout() {
        $this->auth->logout();
        $this->message->set('success', lang('cp_logout'));
        $this->template->set('title', lang('g_login'));
        $this->template->set('bodyid', lang('login'));
        $this->template->load('templates/admin_login_template', 'admin_login', null, 'admin');
    }

    //--------------------------------------------------------------------

    function validate_credentials() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        if ($this->auth->login($username, $password)) {
            redirect('admin');
        } else {
            $this->message->set('warning', lang('g_incorrect_login'));
            $this->session->set_flashdata(array('error' => 'true'));
            redirect('admin/login');
        }
    }

    //--------------------------------------------------------------------
    //forgot password
    function forgot_password() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email Address', 'required');
        if ($this->form_validation->run() == false) {
            //setup the input
            $this->data['email'] = array('name' => 'email',
                'id' => 'email',
            );
            //set any errors and display the form
            $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
            $this->load->view('auth/forgot_password', $this->data);
        } else {
            //run the forgotten password method to email an activation code to the user
            $forgotten = $this->auth->forgotten_password($this->input->post('email'));

            if ($forgotten) { //if there were no errors
                $this->message->set('success', $this->auth->messages());
                redirect("admin/login", 'refresh'); //we should display a confirmation page here instead of the login page
            } else {
                $this->message->set('error', $this->auth->errors());
                redirect("admin/forgot_password", 'refresh');
            }
        }
    }

    //--------------------------------------------------------------------
    //reset password - final step for forgotten password
    public function reset_password($code) {
        $reset = $this->auth->forgotten_password_complete($code);

        if ($reset) {  //if the reset worked then send them to the login page
            $this->session->set_flashdata('message', $this->auth->messages());
            redirect("admin/login", 'refresh');
        } else { //if the reset didnt work then send them back to the forgot password page
            $this->session->set_flashdata('message', $this->auth->errors());
            redirect("admin/forgot_password", 'refresh');
        }
    }

    //--------------------------------------------------------------------
    //change password
    function change_password() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('old', 'Old password', 'required');
        $this->form_validation->set_rules('new', 'New Password', 'required|min_length[' . $this->config->item('min_password_length', 'auth') . ']|max_length[' . $this->config->item('max_password_length', 'auth') . ']|matches[new_confirm]');
        $this->form_validation->set_rules('new_confirm', 'Confirm New Password', 'required');

        if (!$this->auth->logged_in()) {
            redirect('admin/login', 'refresh');
        }
        $user = $this->auth->get_user($this->session->userdata('user_id'));

        if ($this->form_validation->run() == false) { //display the form
            //set the flash data error message if there is one
            //render
            $data = array(
                'title' => 'Change Password',
                'main_content' => 'auth/change_password',
            );
            $this->load->view('admin/template/template', $data);
        } else {
            $identity = $this->session->userdata($this->config->item('identity', 'auth'));

            $change = $this->auth->change_password($identity, $this->input->post('old'), $this->input->post('new'));

            if ($change) { //if the password was successfully changed
                $this->message->set('success', $this->auth->messages());
                $this->logout();
            } else {
                $this->message->set('error', $this->auth->errors());
                redirect('admin/change_password', 'refresh');
            }
        }
    }

    //--------------------------------------------------------------------

    function _is_logged_in() {
        if (!$this->auth->logged_in()) {
            redirect('admin/login');
        }
    }

    //--------------------------------------------------------------------

    function user_management($status = null) {
        //is user logged in
        $this->_is_logged_in();
        //permissions
        $this->auth->restrict('Admin_Users_View');

        $this->load->model('admin_model');
        $userman = $this->admin_model->getusers();

        $data = array(
            'total' => $userman['total'],
            'per_page' => $userman['per_page'],
            'table' => $this->table->generate(),
            'paginate' => $this->pagination->create_links(),
        );
        $this->template->set('title', lang('admin_user_management'));
        $this->template->set('page_title', lang('admin_user_management'));
        $this->template->load('templates/admin_template', 'user_management', $data, 'admin');
    }

    //--------------------------------------------------------------------

    function add_user() {
        //TODO: create add user function
    }

    //--------------------------------------------------------------------

    //TODO: edit and delete roles
    //--------------------------------------------------------------------
    //
    //Image Management Functions
    //
    
    function image_management() {
        //is user logged in
        $this->_is_logged_in();

        $this->load->model('admin_model');
        $getimages = $this->admin_model->get_images();

        $data = array(
            'title' => lang('admin_manage_images'),
            'main_content' => 'admin/image_management',
            'page_title' => lang('admin_manage_images'),
            'paginate' => $this->pagination->create_links(),
            'total' => $getimages['total'],
            'per_page' => $getimages['per_page'],
            'table' => $this->table->generate()
        );
        $this->template->set('title', lang('admin_manage_images'));
        $this->template->set('page_title', lang('admin_manage_images'));
        $this->template->load('templates/admin_template', 'image_management', $data, 'admin');
    }

    //--------------------------------------------------------------------

    function delete_image($image_id) {
        //is user logged in
        $this->_is_logged_in();

        $this->load->model('admin_model');
        $this->admin_model->delete_image($image_id);
        redirect('admin/image_management');
    }

    //--------------------------------------------------------------------

    function system_settings() {
        //is user logged in
        $this->_is_logged_in();

        if ($this->input->post('site')) {
            if (write_config('config', array(
                        'base_url' => $this->input->post('base_url'),
                        'index_page' => $this->input->post('index'),
                        'theme' => $this->input->post('theme')
                    ))) {
                $this->message->set('success', lang('admin_settings_saved'));
            } else {
                $this->message->set('error', lang('admin_settings_error'));
            }
        } elseif ($this->input->post('local')) {
            if (write_config('config', array(
                        'language' => $this->input->post('base_url'),
                        'charset' => $this->input->post('index')
                    ))) {
                $this->message->set('success', lang('admin_settings_saved'));
            } else {
                $this->message->set('error', lang('admin_settings_error'));
            }
        } elseif ($this->input->post('upload')) {

            if (write_config('upload', array(
                        'upload_path' => $this->input->post('upload_path'),
                        'allowed_types' => $this->input->post('allowed_type'),
                        'max_height' => $this->input->post('max_height'),
                        'max_width' => $this->input->post('max_width'),
                        'max_size' => $this->input->post('max_size'),
                        'max_filename' => $this->input->post('max_filename'),
                        'encrypt_names' => $this->input->post('encrypt_names')
                    ))) {
                $this->message->set('success', lang('admin_settings_saved'));
            } else {
                $this->message->set('error', lang('admin_settings_error'));
            }
        }

        $this->template->set('title', lang('admin_system_settings'));
        $this->template->set('page_title', lang('admin_system_settings'));
        $this->template->load('templates/admin_template', 'system_settings', null, 'admin');
    }

    function _is_admin() {
        if (!$this->auth->is_admin()) {
            $this->message->set('error', lang('admin_no_admin'));
            redirect('admin/login');
        }
    }

    function _prev_url() {
        //set previous url
        if (isset($_SERVER['HTTP_REFERER'])) {
            $this->session->set_userdata('prev_url', $_SERVER['HTTP_REFERER']);
        } else {
            $this->session->set_userdata('prev_url', base_url());
        }
    }
    
    function stats() {
        $this->template->set('title', 'title');
        $this->template->load('templates/admin_template', 'stats', null, 'admin');
    }

}

?>
